package com.bestcem.xm.deliver.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.deliver.convert.grpc.DeliverGrpcConvertMapper;
import com.bestcem.xm.deliver.grpc.client.dto.SmsSendingResultDto;
import com.bestcem.xm.deliver.grpc.client.dto.WechatMsgTemplateDto;
import com.bestcem.xm.deliver.grpc.client.dto.WechatOfficialInfoDto;
import com.bestcem.xm.push.grpc.v1.enums.PushSmsTypeEnum;
import com.bestcem.xm.push.grpc.v1.services.*;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 这里应该要换成直接对接微信后台，而不是依赖push服务
 *
 * @ClassName: PushGrpcClient
 * @Author: chenglong.yue
 * @Date: 2022/10/13 16:56
 */
@Slf4j
@Component
public class PushGrpcClient {

    @GrpcClient(GrpcClientNames.DS_PUSH)
    private WechatOfficialAccountServiceGrpc.WechatOfficialAccountServiceBlockingStub stub;

    @GrpcClient(GrpcClientNames.DS_PUSH)
    private PushSmsServiceGrpc.PushSmsServiceBlockingStub smsStub;

    private final com.bestcem.xm.deliver.convert.grpc.DeliverGrpcConvertMapper deliverGrpcConvertMapper;

    public PushGrpcClient(DeliverGrpcConvertMapper deliverGrpcConvertMapper) {
        this.deliverGrpcConvertMapper = deliverGrpcConvertMapper;
    }

    public List<WechatOfficialInfoDto> listAccountInfo(String orgId) {
        ListAccountInfoRequest.Builder builder = ListAccountInfoRequest.newBuilder();
        builder.setOrgId(orgId);
        try {
            ListAccountInfoResponse response = stub.listAccountInfo(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] listAccountInfo, orgId = {} Error; ErrorMsg: {}", orgId, response);
                return Collections.emptyList();
            }
            return deliverGrpcConvertMapper.toWechatOfficialInfoDtoList(response.getInfoList());
        } catch (Exception e) {
            log.error("[deliver] listAccountInfo, orgId = {} Error; ErrorMsg: {}", orgId, e.getMessage());
            return Collections.emptyList();
        }
    }


    public List<WechatMsgTemplateDto> listMsgTemplates(String appId, String orgId) {
        //假的测试
        List<MsgTemplate> list = new ArrayList<>();
        MsgTemplate.Builder builder = MsgTemplate.newBuilder();
        builder.setId("iPk5sOIt5X_flOVKn5GrTFpncEYTojx6ddbt8WYoV5s");
        builder.setTitle("领取奖金提醒");
        builder.setContent("{ {result.DATA} }\\n\\n领奖金额:{ {withdrawMoney.DATA} }\\n领奖  时间:    { {withdrawTime.DATA} }\\n银行信息:{ {cardInfo.DATA} }\\n到账时间:  { {arrivedTime.DATA} }\\n{ {remark.DATA} }");
        builder.setExample("您已提交领奖申请\\n\\n领奖金额：xxxx元\\n领奖时间：2013-10-10 12:22:22\\n银行信息：xx银行(尾号xxxx)\\n到账时间：预计xxxxxxx\\n\\n预计将于 xxxx 到达您的银行卡");
        list.add(builder.build());
        return deliverGrpcConvertMapper.toWechatMsgTemplateDtoList(list);
        /*ListMsgTemplatesRequest.Builder builder = ListMsgTemplatesRequest.newBuilder();
        builder.setOrgId(orgId);
        builder.setAppId(appId);
        try {
            ListMsgTemplatesResponse response = stub.listMsgTemplates(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] listMsgTemplates, appId = {} Error; ErrorMsg: {}", appId, response);
                return Collections.emptyList();
            }
            return deliverGrpcConvertMapper.toWechatMsgTemplateDtoList(response.getTemplatesList());
        } catch (Exception e) {
            log.error("[deliver] listMsgTemplates, appId = {} Error; ErrorMsg: {}", appId, e.getMessage());
            return Collections.emptyList();
        }*/
    }


    public Integer getTemplateMsgStatus(String msgId) {
        //todo 假的
        return 1;
        /*GetTemplateMsgStatusRequest.Builder builder = GetTemplateMsgStatusRequest.newBuilder();
        builder.setId(Long.parseLong(msgId));
        try {
            GetTemplateMsgStatusResponse response = stub.getTemplateMsgStatus(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] getTemplateMsgStatus, msgId = {} Error; ErrorMsg: {}", msgId, response);
                return null;
            }
            return response.getMsgStatus().getNumber();
        } catch (Exception e) {
            log.error("[deliver] getTemplateMsgStatus, msgId = {} Error; ErrorMsg: {}", msgId, e);
            return null;
        }*/
    }

    public String sendTemplateMsg(String org_id, String app_id, String open_id, String template_id, String link, Map<String, String> template_params) {
        //假的
        return new ObjectId().toHexString();
        /*SendTemplateMsgRequest.Builder builder = SendTemplateMsgRequest.newBuilder();
        builder.setOrgId(org_id);
        builder.setAppId(app_id);
        builder.setOpenId(open_id);
        builder.setTemplateId(template_id);
        builder.setUrl(link);
        builder.putAllParams(template_params);
        try {
            SendTemplateMsgResponse response = stub.sendTemplateMsg(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] sendTemplateMsg Error;");
                return null;
            }
            return String.valueOf(response.getId());
        } catch (Exception e) {
            log.error("[deliver] sendTemplateMsg Error; ErrorMsg: {}", e.getMessage());
            return null;
        }*/
    }


    public SmsSendingResultDto sendSingleSms(String mobile, String content, String componentCode) {
        SendSingleSmsRequest build = SendSingleSmsRequest.newBuilder()
                .setSmsType(PushSmsTypeEnum.PushSmsType.forNumber(2))
                .setPhone(mobile)
                .setContent(content)
                .setComponentCode(componentCode)
                .build();
        SendSingleSmsResponse response = smsStub.sendSingleSms(build);

        // 校验查询结果
        if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
            log.error("[deliver] push sendSingleSms发送短信失败：mobile:{} ", mobile);
            return null;
        }
        return deliverGrpcConvertMapper.sendSingleResultGrpc2Dto(response.getResult());
    }
}
